<template>
  <el-container>
    <el-header>
      <!--导航条 -->
      <Data_navigate></Data_navigate>
    </el-header>
    <el-main>
      <el-container>
        <el-aside width="284px" style="padding-left: 10px;;">
          <Data_tree :isShowCtrl="true" :treeReloadMittKey="PageEvent.data_do_reload_tree_node"
            :chooseNodeMittKey="PageEvent.data_choose_tree" loadTreeUrl="api/localorg/tree"></Data_tree>
        </el-aside>
        <el-container>
          <el-header>
            <!--普通查询条件  isShowQueryPlus是否展示高级查询-->
            <Data_querys placeholder="姓名|登录名" :isShowQueryPlus="true">
            </Data_querys>
            <div class="farm2-data-buttons-operators">
              <el-button type="primary" @click="openDataFormClick" icon="Plus" plain>创建</el-button>
              <el-dropdown style="margin-left: 20px;margin-right: 20px;">
                <el-button icon="Unlock" type="primary" plain>
                  修改密码<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="resetPasswordClick">重置密码</el-dropdown-item>
                    <el-dropdown-item @click="updatePasswordClick">修改密码</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-dropdown style="margin-right: 20px;">
                <el-button icon="Collection" type="primary" plain>
                  导入导出<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="exportUserClick">导出用户</el-dropdown-item>
                    <el-divider style="margin-top: 4px;margin-bottom: 4px;">
                    </el-divider>
                    <el-dropdown-item @click="downloadTemplateClick">下载模板</el-dropdown-item>
                    <el-dropdown-item @click="openUploadFormClick">导入用户</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-button type="danger" icon="Delete" @click="datasDeleteClick" plain>删除</el-button>
            </div>
          </el-header>
          <el-main>
            <!--数据集-->
            <div class="farm2-data-table">
              <el-table v-loading="loadingFlag" :data="dataResult.data" style="width: 100%" :stripe="true"
                @selection-change="handleSelectionChange" :highlight-current-row="true" class="table"
                @sort-change="(data: SortInfo) => { doDataQuery(tableUtils.getSortQuery(data)) }">
                <el-table-column fixed="left" type="selection" width="55" />
                <el-table-column fixed="left" sortable="custom" prop="NAME" label="姓名" min-width="150px" />
                <el-table-column sortable="custom" prop="LOGINNAME" label="登录名" min-width="120" />
                <el-table-column sortable="custom" prop="ORGNAME" label="组织机构" min-width="120" />
                <el-table-column prop="TYPE" :formatter="dic.formatTYPE" label="类型" min-width="120" />
                <el-table-column prop="STATE" :formatter="dic.formatSTATE" label="状态" min-width="120" />
                <el-table-column sortable="custom" prop="LOGINTIME" :formatter="dic.formatTime" label="登录时间"
                  width="140" />
                <el-table-column prop="NOTE" label="备注" width="300" />
                <el-table-column fixed="right" label="操作" width="200">
                  <template #default="scope">
                    <el-button link type="primary" icon="View" size="small" @click="dataViewClick(scope.row)">
                      查看
                    </el-button>
                    <el-button link type="primary" icon="Edit" size="small" @click="dataEditClick(scope.row)">
                      修改
                    </el-button>
                    <el-button link type="success" icon="Delete" size="small"
                      @click="dataDeleteClick(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-main>
          <el-footer>
            <!--分页框-->
            <Data_page :remoteData="dataResult" />
          </el-footer>
        </el-container>
      </el-container>
    </el-main>
  </el-container>
  <!--高级查询表单-->
  <User_form_query></User_form_query>
  <!--数据实体表单-->
  <User_form_data></User_form_data>
  <!--修改密码-->
  <User_from_password update-url="api/localuser/resetpassword" ref="rePasswordForm"></user_from_password>
  <!--导入用户-->
  <User_data_upload></User_data_upload>
</template>
<script setup lang="ts">
import Data_navigate from '@/components/datas/data_navigate.vue';
import User_data_upload from './components/user_data_upload.vue';
import Data_page from '@/components/datas/data_page.vue';
import Data_tree from '@/components/datas/data_tree.vue';
import { onBeforeMount, onBeforeUnmount, onMounted, provide, reactive, ref } from 'vue';
import farm2Request from '@/service/remoteRequests/Farm2Request';
import Data_querys from '@/components/datas/data_querys.vue';
import notice from '@/components/msg/FarmNotice';
import QueryUtils from '@/hook/farmQueryUtils'
import mitt from 'mitt';
import { PageEvent } from '@/types/commons/PageEvent';
import type { SortInfo } from '@/types/elementplus/SortInfo';
import type { DataQuery } from '@/types/commons/DataQuery';
import type { DataResult } from '@/types/commons/DataResult';
import tableUtils from '@/hook/farmTableUtils';
import User_form_query from './components/user_form_query.vue';
import User_form_data from './components/user_form_data.vue';
import User_from_password from './components/user_form_password.vue';
import dic from './utils/dictinarys'
import { getCreatType, getUpdateType, getViewType, type FormParam } from '@/types/commons/FormType';
import Farm2Request from '@/service/remoteRequests/Farm2Request';
import { RequestTypeEnum } from '@/types/commons/RequestTypeEnum';
import { ElMessageBox } from 'element-plus';
import { MittKeysEnum } from './utils/mittKeys'










const eventBus = mitt();
const dataResult: DataResult = reactive(QueryUtils.getDefaultResult());
const dataQuery: DataQuery = reactive({});
const loadingFlag = ref(true);
const multipleSelection = ref([]);
const handleSelectionChange = (selection: []) => {
  multipleSelection.value = selection;
};

const rePasswordForm = ref();



/**
 * 后台检索查询用户--HTTP(POST)
 * @param query
 */
const doDataQuery = async (query?: DataQuery) => {
  farm2Request.search('api/localuser/query', Object.assign(dataQuery, query), loadingFlag)
    .then((remoteResult: DataResult) => {
      Object.assign(dataResult, remoteResult);
    })
    .catch((msg: Error) => {
      notice.byError(msg.message);
    });
}

/**
 * 打开附件上传窗口-事件
 */
const openUploadFormClick = () => {
  eventBus.emit(MittKeysEnum.openUploadForm, { isOpen: true, type: <FormParam>{ type: { key: "creat", title: "上传导入数据" } } });
}

/**
 * 后台批量删除--HTTP(DELETE)
 * @param ids
 */
const doDataDelete = (ids: string[]) => {
  Farm2Request.submit(
    'api/localuser/batch',
    RequestTypeEnum.delete,
    loadingFlag, ids
  ).then(() => {
    doDataQuery();
  }).catch((msg: Error) => {
    notice.byError(msg.message);
  });
}

/**
 * 导出用户
 */
const exportUserClick = () => {
  Farm2Request.downloadReport("api/localuser/report",
    dataQuery, "users.xls",
    () => { notice.bySuccess("报表导出中..."); },
    () => { notice.bySuccess("导出成功"); });
}

/**
 * 下载模板
 */
const downloadTemplateClick = () => {
  Farm2Request.downloadReport("api/localuser/downtemplate",
    {}, "userImportTemplate.xls",
    () => { notice.bySuccess("模板下载中..."); },
    () => { notice.bySuccess("下载成功"); });
}

/**
 *重置默认密码-事件
 * @param row
 */
const resetPasswordClick = () => {
  const selection: { ID: string; }[] = multipleSelection.value;
  const ids = selection.map(item => item.ID);
  ElMessageBox.confirm('当前选定' + ids.length + '条数据,该操作无法恢复,确认重置密码?', { icon: 'QuestionFilled' })
    .then(() => {
      Farm2Request.submit(
        'api/localuser/defaultpassword',
        RequestTypeEnum.post,
        loadingFlag, ids
      ).then(() => {
        notice.bySuccess("密码已重置");
      }).catch((msg: Error) => {
        notice.byError(msg.message);
      });
    }).catch(() => { });
}

/**
 * 重置指定密码-事件
 * @param row
 */
const updatePasswordClick = () => {
  const selection: { LOGINNAME: string; }[] = multipleSelection.value;
  const loginnames = selection.map(item => item.LOGINNAME);
  if (loginnames.length <= 0) {
    ElMessageBox.alert("请选择数据");
    return null;
  }
  rePasswordForm.value.openWin(loginnames);
}



/**
 * 打开数据更新窗口-事件
 * @param row 选定行数据
 */
const dataEditClick = (row: { ID: string }) => {
  eventBus.emit(PageEvent.data_form_open, { isOpen: true, type: <FormParam>{ type: getUpdateType(), id: row.ID, data: row } });
}

/**
 * 删除一条-事件
 * @param row 选定行数据
 */
const dataDeleteClick = (row: { ID: string }) => {
  ElMessageBox.confirm('确认删除?', { icon: 'QuestionFilled' })
    .then(() => {
      doDataDelete([row.ID]);
    }).catch(() => { });
}

/**
 * 删除多条-事件
 * @param row
 */
const datasDeleteClick = () => {
  const selection: { ID: string; }[] = multipleSelection.value;
  const ids = selection.map(item => item.ID);
  ElMessageBox.confirm('当前选定' + ids.length + '条数据,确认删除?', { icon: 'QuestionFilled' })
    .then(() => {
      doDataDelete(ids);
    }).catch(() => { });
}



/**
 * 打开数据查看窗口-事件
 * @param row 选定行数据
 */
const dataViewClick = (row: { ID: string }) => {
  eventBus.emit(PageEvent.data_form_open, { isOpen: true, type: <FormParam>{ type: getViewType(), id: row.ID, data: row } });
}


/**
 * 打开数据创建窗口-事件
 */
const openDataFormClick = () => {
  eventBus.emit(PageEvent.data_form_open, { isOpen: true, type: <FormParam>{ type: getCreatType() } });
}

/**
 * 选中树节点
 * @param row
 */
const chooseTreeNode = (row: { NAME: string, ID: string }) => {
  doDataQuery({ rules: [{ key: 'ORGID', value: row.ID, compara: '=' }] });
}



onMounted(() => {

  doDataQuery();

  eventBus.on(PageEvent.data_do_query, (query) => {
    doDataQuery(query as DataQuery);
  });
  eventBus.on(PageEvent.data_choose_tree, (row) => {
    chooseTreeNode(row as { NAME: string, ID: string });
  })
});
onBeforeMount(() => {
  provide('eventBus', eventBus);
});
onBeforeUnmount(() => {
  eventBus.all.clear();
})
</script>
